package team.tunan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import team.tunan.dto.StockPageDto;
import team.tunan.entity.Stock;
import team.tunan.exception.BusinessException;
import team.tunan.mapper.StockMapper;
import team.tunan.service.IStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import static team.tunan.common.HttpCodeEnum.OPERATION_ERROR;
import static team.tunan.common.HttpCodeEnum.SYSTEM_ERROR;

/**
 * <p>
 * 产品表	 服务实现类
 * </p>
 *
 * @author sqx
 * @since 2023-12-24
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public int insertStock(Stock stock) {
        //checkStock(stock);
        return stockMapper.insert(stock);
    }

    @Override
    public int deleteStock(String id) {
        return stockMapper.deleteById(id);
    }

    @Override
    public int updateStock(Stock stock) {
        //checkStock(stock);
        return stockMapper.updateById(stock);
    }

    @Override
    public void addStockNumber(Integer id, Integer stockinQuantity) {
        Stock stock = stockMapper.selectById(id);
        stock.setNumber(stock.getNumber()+stockinQuantity);
        stockMapper.updateById(stock);
    }

    @Override
    public void reduceStockNumber(Integer stockId, Integer number) {
        Stock stock = stockMapper.selectById(stockId);
        if(stock.getNumber()<number){
            throw new BusinessException(SYSTEM_ERROR.getCode(), "商品库存不足");
        }
        stock.setNumber(stock.getNumber()-number);
        stockMapper.updateById(stock);
    }

    @Override
    public Page<Stock> selectPage(StockPageDto stockPageDto) {
        LambdaQueryWrapper<Stock> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(stockPageDto.getStockName())&&!"null".equals(stockPageDto.getStockName())){
            queryWrapper.like(Stock::getStockName,stockPageDto.getStockName());
        }
        Page<Stock> page = new Page<>(stockPageDto.getCurrentPage(), stockPageDto.getPageSize());
        Page<Stock> stockPage = stockMapper.selectPage(page, queryWrapper);
        return stockPage;
    }

    @Override
    public Stock selectByStockId(Integer stockId) {
        return stockMapper.selectById(stockId);
    }

    private void checkStock(Stock stock) {
        if(stock.getNumber()<0) {
            throw new BusinessException(OPERATION_ERROR.getCode(), "库存不能小于0");
        }
        if(stock.getPrice().doubleValue() < 0) {
            throw new BusinessException(OPERATION_ERROR.getCode(), "价格不能小于0");
        }
    }
}
